package com.eastmoney.emis.edda.infrastructure.hsbc.aop;

import com.eastmoney.emis.context.helper.ThreadPoolHelper;
import com.eastmoney.emis.context.helper.UserActionHelper;
import com.eastmoney.emis.edda.infrastructure.hsbc.annotation.HsbcLog;
import com.eastmoney.emis.edda.infrastructure.hsbc.dto.HsbcEddaBaseResp;
import com.eastmoney.emis.logger.LoggerFactory;
import com.eastmoney.emis.utils.common.po.UserAction;
import com.eastmoney.emis.utils.common.sensitive.SensitiveUtils;
import com.eastmoney.emis.utils.common.utils.JSONUtils;
import com.google.common.collect.Maps;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Method;
import java.util.Map;

@Component
@Aspect
public class HsbcLogAspect {
    private static final Logger log = LoggerFactory.getLogger(HsbcLogAspect.class);
    private static final Logger loggerModule = LoggerFactory.getModuleLogger(HsbcLogAspect.class, "thirdParty", "user_action");

    @Pointcut("@annotation(com.eastmoney.emis.edda.infrastructure.hsbc.annotation.HsbcLog)")
    public void pointcut() {

    }


    @AfterReturning(value = "pointcut()", returning = "response")
    public void afterReturning(JoinPoint joinPoint, HsbcEddaBaseResp response) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        HsbcLog hsbcLog = method.getAnnotation(HsbcLog.class);
        UserAction userAction = UserActionHelper.getUserAction(UserActionHelper.Level.INFO, hsbcLog.action());
        if (!response.success() || !ObjectUtils.isEmpty(response.ProcessResult.RejectReasonList)) {
            userAction.setResult("1");
            userAction.setLogType("WARN");
            userAction.setErrorMsg(response.result());
        }
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("params", SensitiveUtils.acquire(joinPoint.getArgs()));
        userAction.setInParam(paramMap);
        userAction.buildOutParam(response);
        ThreadPoolHelper.threadPoolTaskExecutor().submit(() -> loggerModule.info(JSONUtils.toJSONString(userAction)));
    }


}
